import React, { useState } from 'react';
import { 
  Form, 
  Input, 
  Button, 
  Card, 
  message, 
  Space,
  Typography,
  Steps,
  Alert
} from 'antd';
import { 
  ArrowLeftOutlined, 
  MailOutlined,
  LockOutlined,
  CheckCircleOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone
} from '@ant-design/icons';
import { useNavigate, Link } from 'react-router-dom';
import styled from '@emotion/styled';

const { Title, Text } = Typography;
const { Step } = Steps;

interface ForgotPasswordFormValues {
  email: string;
  verificationCode: string;
  newPassword: string;
  confirmPassword: string;
}

// Styled Components
const ForgotPasswordContainer = styled.div`
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
`;

const BackButton = styled(Button)`
  position: absolute;
  top: 20px;
  left: 20px;
  color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  
  &:hover {
    background: rgba(255, 255, 255, 0.2);
    border-color: rgba(255, 255, 255, 0.5);
    color: #fff;
  }
`;

const ForgotPasswordContent = styled.div`
  width: 100%;
  max-width: 450px;
`;

const StyledCard = styled(Card)`
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  
  .ant-card-body {
    padding: 40px 32px;
  }
`;

const ForgotPasswordHeader = styled.div`
  text-align: center;
  margin-bottom: 24px;
  
  h2 {
    margin-bottom: 8px;
    color: #1f2937;
    font-weight: 600;
  }
`;

const ActionButton = styled(Button)`
  height: 48px;
  border-radius: 8px;
  font-weight: 500;
  font-size: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  }
`;

const SecondaryButton = styled(Button)`
  height: 48px;
  border-radius: 8px;
  font-weight: 500;
  font-size: 16px;
  
  &:hover {
    transform: translateY(-1px);
  }
`;

const StyledLink = styled(Link)`
  color: #667eea;
  font-weight: 500;
  
  &:hover {
    color: #5a6fd8;
  }
`;

const StyledSteps = styled(Steps)`
  margin-bottom: 32px;
  
  .ant-steps-item-title {
    font-size: 14px;
  }
`;

const VerificationCodeSection = styled.div`
  display: flex;
  gap: 12px;
`;

const SendCodeButton = styled(Button)`
  white-space: nowrap;
  min-width: 120px;
`;

const SuccessSection = styled.div`
  text-align: center;
  padding: 20px 0;
  
  .success-icon {
    font-size: 64px;
    color: #52c41a;
    margin-bottom: 16px;
  }
`;

const StyledInput = styled(Input)`
  border-radius: 6px;
  border: 1px solid #d1d5db;
  transition: all 0.3s;
  
  &:hover,
  &:focus,
  &.ant-input-affix-wrapper-focused {
    border-color: #667eea;
    box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
  }
`;

const StyledPasswordInput = styled(Input.Password)`
  border-radius: 6px;
  border: 1px solid #d1d5db;
  transition: all 0.3s;
  
  &:hover,
  &:focus,
  &.ant-input-affix-wrapper-focused {
    border-color: #667eea;
    box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
  }
`;

const StyledFormItem = styled(Form.Item)`
  .ant-form-item-label {
    font-weight: 500;
    
    > label {
      color: #374151;
    }
  }
`;

const LoginSection = styled.div`
  text-align: center;
  margin-top: 24px;
`;

const AlertContainer = styled.div`
  margin-bottom: 16px;
`;

// 修复 Emotion 组件选择器问题 - 使用类名选择器替代组件选择器
const MobileWrapper = styled.div`
  @media (max-width: 480px) {
    .forgot-password-container {
      padding: 16px;
    }
    
    .back-button {
      top: 16px;
      left: 16px;
    }
    
    .styled-card .ant-card-body {
      padding: 24px 20px;
    }
    
    .verification-section {
      flex-direction: column;
    }
    
    .send-code-button {
      min-width: 100%;
      margin-top: 8px;
    }
  }
`;

const ForgotPasswordPage: React.FC = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [countdown, setCountdown] = useState(0);
  const [email, setEmail] = useState('');

  const handleBack = () => {
    navigate(-1);
  };

  // 发送验证码
  const handleSendCode = async () => {
    try {
      await form.validateFields(['email']);
      const values = form.getFieldsValue();
      setEmail(values.email);
      
      setLoading(true);
      // 模拟发送验证码
      await mockSendVerificationCode(values.email);
      message.success('验证码已发送到您的邮箱');
      
      // 开始倒计时
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
      
      // 进入下一步
      setCurrentStep(1);
    } catch (error) {
      message.error('请输入有效的邮箱地址');
    } finally {
      setLoading(false);
    }
  };

  // 验证验证码
  const handleVerifyCode = async (values: Partial<ForgotPasswordFormValues>) => {
    setLoading(true);
    try {
      await mockVerifyCode(values.verificationCode);
      setCurrentStep(2);
    } catch (error) {
      message.error('验证码错误，请重新输入');
    } finally {
      setLoading(false);
    }
  };

  // 重置密码
  const handleResetPassword = async (values: ForgotPasswordFormValues) => {
    setLoading(true);
    try {
      await mockResetPassword(values.newPassword);
      setCurrentStep(3);
      message.success('密码重置成功');
    } catch (error) {
      message.error('密码重置失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const onFinish = async (values: ForgotPasswordFormValues) => {
    if (currentStep === 0) {
      await handleSendCode();
    } else if (currentStep === 1) {
      await handleVerifyCode(values);
    } else if (currentStep === 2) {
      await handleResetPassword(values);
    }
  };

  // 模拟发送验证码
  const mockSendVerificationCode = (email: string): Promise<void> => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, 1500);
    });
  };

  // 模拟验证验证码
  const mockVerifyCode = (code: string | undefined): Promise<void> => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (code === '123456') {
          resolve();
        } else {
          reject(new Error('验证码错误'));
        }
      }, 1000);
    });
  };

  // 模拟重置密码
  const mockResetPassword = (newPassword: string): Promise<void> => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, 1500);
    });
  };

  const steps = [
    {
      title: '验证邮箱',
      content: (
        <>
          <AlertContainer>
            <Alert 
              message="请输入您注册时使用的邮箱地址，我们将发送验证码到该邮箱" 
              type="info" 
              showIcon 
            />
          </AlertContainer>
          <StyledFormItem
            name="email"
            label="邮箱地址"
            rules={[
              { required: true, message: '请输入邮箱地址!' },
              { type: 'email', message: '请输入有效的邮箱地址!' }
            ]}
          >
            <StyledInput 
              prefix={<MailOutlined />} 
              placeholder="请输入您的邮箱地址" 
            />
          </StyledFormItem>
        </>
      )
    },
    {
      title: '输入验证码',
      content: (
        <>
          <AlertContainer>
            <Alert 
              message={`验证码已发送到 ${email}，请输入6位数字验证码`} 
              type="info" 
              showIcon 
            />
          </AlertContainer>
          <StyledFormItem
            name="verificationCode"
            label="验证码"
            rules={[
              { required: true, message: '请输入验证码!' },
              { len: 6, message: '验证码必须是6位数字!' },
              { pattern: /^\d+$/, message: '验证码只能是数字!' }
            ]}
          >
            <VerificationCodeSection className="verification-section">
              <StyledInput 
                placeholder="请输入6位验证码" 
                maxLength={6}
              />
              <SendCodeButton 
                className="send-code-button"
                onClick={handleSendCode}
                disabled={countdown > 0}
                loading={loading}
              >
                {countdown > 0 ? `${countdown}秒后重发` : '重新发送'}
              </SendCodeButton>
            </VerificationCodeSection>
          </StyledFormItem>
        </>
      )
    },
    {
      title: '设置新密码',
      content: (
        <>
          <AlertContainer>
            <Alert 
              message="请设置您的新密码" 
              type="info" 
              showIcon 
            />
          </AlertContainer>
          <StyledFormItem
            name="newPassword"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码!' },
              { min: 6, message: '密码至少6个字符!' },
              { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, message: '必须包含大小写字母和数字!' }
            ]}
          >
            <StyledPasswordInput
              prefix={<LockOutlined />}
              placeholder="请输入新密码"
              iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
            />
          </StyledFormItem>

          <StyledFormItem
            name="confirmPassword"
            label="确认密码"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认密码!' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致!'));
                },
              }),
            ]}
          >
            <StyledPasswordInput
              prefix={<LockOutlined />}
              placeholder="请再次输入新密码"
              iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
            />
          </StyledFormItem>
        </>
      )
    },
    {
      title: '完成',
      content: (
        <SuccessSection>
          <CheckCircleOutlined className="success-icon" />
          <Title level={3}>密码重置成功</Title>
          <Text type="secondary">
            您的密码已成功重置，现在可以使用新密码登录您的账户
          </Text>
        </SuccessSection>
      )
    }
  ];

  return (
    <MobileWrapper>
      <ForgotPasswordContainer className="forgot-password-container">
        <BackButton 
          className="back-button"
          type="text" 
          icon={<ArrowLeftOutlined />} 
          onClick={handleBack}
        >
          返回
        </BackButton>
        
        <ForgotPasswordContent>
          <StyledCard className="styled-card">
            <ForgotPasswordHeader>
              <Title level={2}>重置密码</Title>
              <Text type="secondary">按照步骤重置您的账户密码</Text>
            </ForgotPasswordHeader>

            <StyledSteps current={currentStep}>
              {steps.map((item, index) => (
                <Step key={index} title={item.title} />
              ))}
            </StyledSteps>

            <Form
              form={form}
              name="forgotPassword"
              onFinish={onFinish}
              layout="vertical"
              size="large"
            >
              {steps[currentStep].content}

              {currentStep < 3 && (
                <Form.Item>
                  <Space direction="vertical" style={{ width: '100%' }} size="middle">
                    <ActionButton 
                      type="primary" 
                      htmlType="submit" 
                      loading={loading}
                      block
                    >
                      {currentStep === 0 ? '发送验证码' : 
                       currentStep === 1 ? '验证' : 
                       '重置密码'}
                    </ActionButton>
                    
                    {currentStep > 0 && (
                      <SecondaryButton 
                        onClick={() => setCurrentStep(currentStep - 1)}
                        block
                      >
                        上一步
                      </SecondaryButton>
                    )}
                  </Space>
                </Form.Item>
              )}

              {currentStep === 3 && (
                <Form.Item>
                  <ActionButton 
                    type="primary" 
                    onClick={() => navigate('/login')}
                    block
                  >
                    立即登录
                  </ActionButton>
                </Form.Item>
              )}
            </Form>

            <LoginSection>
              <Space>
                <Text>想起密码了?</Text>
                <StyledLink to="/login">返回登录</StyledLink>
              </Space>
            </LoginSection>
          </StyledCard>
        </ForgotPasswordContent>
      </ForgotPasswordContainer>
    </MobileWrapper>
  );
};

export default ForgotPasswordPage;